<?php
namespace Home\Controller;

use Think\Controller;
use Base\FrontController;

/**
 * @name 前端提交异步数据到数据库 ，访问本接口下任何方法均要求session中已保留注册用户信息
 * @author perry
 *
 */
class ApiController extends FrontController
{

    // private $weixin_user;

    function _initialize()
    {
        parent::_initialize();
        $this->uploadRootPath = './Uploads/';
        $this->uploadSubTmpPath = 'nail_photos/tmp/';
        $this->uploadSubPath = 'nail_photos/';
    }

    /**
     * 上传图片文件到/Uploads/nail_photos/tmp/目录下
     * 如果有旧文件要删除,通过I('osn')传递进来
     */
    public function cupload()
    {
        try {
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize = 1457280;// 设置附件上传大小
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath = $this->uploadRootPath; // 设置附件上传根目
            //子目录创建方式
            $upload->subName = $this->uploadSubTmpPath;
            $re = $upload->upload();
            $err = $upload->getError();
            if ($err) {
                throw new \Exception($err, -1);
            }
            //判断是否有旧文件要删除
            $old_file = I('osn');
            if ($old_file) {
                $filepath = $upload->rootPath . $upload->subName . $old_file;
                unlink($filepath);
            }
            $info['savename'] = $re['imagefile']['savename'];
            $this->customReturn(1, array('sn' => $re['imagefile']['savename']));
        } catch (\Exception $ecx) {
            $this->customReturn(-1, array('errmsg' => $ecx->getMessage(), 'errcode' => $redirect_url));
        }
    }

    /**
     * 转换session
     * @param 名称 $key
     * @param 值 $value
     */
    private function changeSession($key, $value)
    {
        $_SESSION[$key] = $value;
        session($key, $value);
    }


    /**消费者注册接口
     *地址 Home/Api/index
     * 传入参数:姓名：realname(格式纯文本)  手机：phone(手机格式11位)  省：r_province(格式为纯文本)     市：r_city(格式为纯文本)   邀请码：invite_code (随机字符)
     * 性别：r_sex (1=男，2=女)     灰指甲部位：nail_type(0=未透露,1=手指,2=脚趾',)上传照片文件名: photo_name(jpg,png,…)
     * 返回值格式：array('succ'=>a1,'data'=>a2)
     * 返回值:如果a1==1时，表示接口成功调用，a2里data包含正确的返回值，
     * {"succ": 1,"data": {"nickname": "xxxx","headimgurl": "xxxx"}}
     * a1如果不等于1则表示出错了，返回data值都是错误代码，
     * 返回data值结果如下：
     * array('errcode'=>1001, 'errmsg'=>请填写正确的手机号码)
     * array('errcode'=>1002, 'errmsg'=>’请输入您的姓名哦’)
     * array('errcode'=>1004, 'errmsg'=>' r_sex参数为勾选或者参数格式不对只能为1和2')
     * array('errcode'=>1005, 'errmsg'=>' nail_type参数为勾选或者参数格式不对只能为0和1和2)
     *array('errcode'=>101, 'errmsg'=>’ 图片格式不对’)
     * array('errcode'=>11, 'errmsg'=>’ 手机号已存在’)
     * array('errcode'=>116, 'errmsg'=>’ 省份未找到’)
     * array('errcode'=>126, 'errmsg'=>’ 城市未找到’)
     * array('errcode'=>1999, 'errmsg'=>’网络原因保存您的注册信息未成功,请稍候再试’)
     * array('errcode'=>1704, 'errmsg'=>' age参数需大于0')
     * array('errcode'=>1804, 'errmsg'=>' NailProblems参数为勾选或者参数格式不对只能为1和2')
     */
    public function index_user()
    {
        $ajaxdata = array();
        try {
            $d = C('shengshi');
            $dd = json_decode($d, true);
            $realname = I('realname');
            $phone = I('phone');
            $r_province = I('r_province');
            $r_city = I('r_city');
            $invite_code = I('invite_code');
            $r_sex = I('r_sex');
            $nail_type = I('nail_type');
            $age = I('age');
            $NailProblems = I('nailproblems');
            if (ic_checkUnEmpty($realname)) {
                $map['realname'] = $realname;
            } else {
                $ajaxdata['errcode'] = '1002';
                $ajaxdata['errmsg'] = '请输入您的姓名哦';
                $this->customReturn(1002, $ajaxdata);
            }
            if (ic_isPosInt($age)) {
                if($age>115){
                    $ajaxdata['errcode'] = 1705;
                    $ajaxdata['errmsg'] = "您的年龄是不是过大哦,请检查";
                    $this->customReturn(1705, $ajaxdata);
                }
                $map['age'] = $age;
            } else {
                $ajaxdata['errcode'] = 1704;
                $ajaxdata['errmsg'] = "请正确输入您的年龄";
                $this->customReturn(1704, $ajaxdata);
            }
            $datae = M('apply_user')->field('phone')->select();//验证手机号唯一
            foreach ($datae as $k => $value) {
                if ($phone == $datae[$k]['phone']) {
                    $ajaxdata['errcode'] = 11;
                    $ajaxdata['errmsg'] = "您输入的手机号已被注册,请检查哦";
                    $this->customReturn(11, $ajaxdata);
                }
            }
            if (ic_isCellPhone($phone) == ture) {
                $map['phone'] = $phone;
            } else {
                $ajaxdata['errcode'] = 1001;
                $ajaxdata['errmsg'] = "请填写正确的手机号码";
                $this->customReturn(1001, $ajaxdata);
            }
            if ($invite_code) {
                $map['invite_code'] = $invite_code;
            }
            $ghh = false;//设定默认值
            $j = 0;
            foreach ($dd['citylist'] as $k => $value) {
                if ($r_province == $value['p']) {
                    $ghh = true;
                    $j = $k;
                    break;
                }
            }
            if (!$ghh) {
                $ajaxdata['errcode'] = 116;
                $ajaxdata['errmsg'] = "请选择您所在的省份";
                $this->customReturn(116, $ajaxdata);
            }
            if ($r_province) {
                $map['r_province'] = $r_province;
            }
            $bbb = false;//设定默认值
            foreach ($dd['citylist'][$j]['c'] as $k => $value) {
                if ($r_city == $value['n']) {
                    $bbb = true;
                    break;
                }
            }
            if (!$bbb) {
                $ajaxdata['errcode'] = 126;
                $ajaxdata['errmsg'] = "城市未找到";
                $this->customReturn(126, $ajaxdata);
            }
            if ($r_city) {
                $map['r_city'] = $r_city;
            }
            if (ic_isPosInt($r_sex) and ($r_sex == 1 || $r_sex == 2)) {
                $map['r_sex'] = $r_sex;
            } else {
                $ajaxdata['errcode'] = 1004;
                $ajaxdata['errmsg'] = "请正确选择您的性别".$r_sex;
                $this->customReturn(1004, $ajaxdata);
            }
            if (ic_checkUnEmpty($nail_type) and ($nail_type == 1 || $nail_type == 2)) {
                $map['nail_type'] = $nail_type;
            } else {
                $ajaxdata['errcode'] = 1005;
                $ajaxdata['errmsg'] = "请正确选择您的问题指甲部位".$nail_type;
                $this->customReturn(1005, $ajaxdata);
            }

            if (ic_isPosInt($NailProblems) and ($NailProblems == 1 || $NailProblems == 2)) {
                $map['nailproblems'] = $NailProblems;
            } else {
                $ajaxdata['errcode'] = 1804;
                $ajaxdata['errmsg'] = "指甲问题请选择正确的选项哦";
                $this->customReturn(1804, $ajaxdata);
            }
            $data_id = $this->weixin_user['id'];
            $map['type'] = 1;
            //判断用户是否上传了图片
            $photo_name = I('photo_name', false);
            if ($photo_name) {
                $pmodel = D('NailPhoto');
                $pmodel->newRecord($photo_name, $data_id);
            }
            //保存用户信息
            $updateRe = M('apply_user')->where('id=' . $data_id)->save($map);
            if (!$updateRe) {
                $ajaxdata['errcode'] = 1999;
                $ajaxdata['errmsg'] = "网络原因保存您的注册信息未成功,请稍候再试";
                $this->customReturn(1999, $ajaxdata);
            }
            $data = M('apply_user')->where(array('id' => $data_id))->find();
            $data['just_registed'] = 1; //标示此用户刚注册,可以参加第一轮注册轮抽奖
            $this->changeSession(C('weixin_session_key'), $data);
            $succ = 1;
            $datas = array();
            $datas['nickname'] = $data['nickname'];
            $datas['headimgurl'] = $data['headimgurl'];
            $datas['realname'] = $data['realname'];
            $this->customReturn($succ, $datas);
        } catch (\Exception $exc) {
            //返回失败信息
            $succ = $exc->getCode() == 1 ? -1 : $exc->getCode();
            $datas = array('errcode' => $succ, 'errmsg' => $exc->getMessage());
            $this->customReturn($succ, $datas);
        }

    }

    /** 消费者刮奖接口
     *接口地址Home/Api/gjjk
     *访问方式:GET,POST
     *返回值: array('succ'=>a1,'data'=>a2）
     * 如果a1==1时，表示接口成功调用，a2里data包含正确的返回值，
     * 格式如下：(gift_id为0表示未中奖,否则奖品名称在gift_name中)
     * (need_contact_info 如果为1,需要弹窗让用户留下联系信息)
     * {"id":"1","gift_id":"xxx","gift_name":"xxxxx"," need_contact_info:"xxx"}
      * a1如果不等于1则表示出错了，返回data值都是错误代码，
     * array('errcode'=>666, 'errmsg'=>’网络故障,摇奖失败’)
     * array('errcode'=>215, 'errmsg'=>’网络故障,刮奖失败,请稍候再试哦’)
     * array('errcode'=>1701, 'errmsg'=>’您不能参与抽奖哦,请联系管理员’)
     * array('errcode'=>1702, 'errmsg'=>’您7天内已参与过抽奖哦,请6天23小时59分后再来^_^’)
     */

    public function gjjk()
    {
        try {
//            $round = I('round');
            if ($this->weixin_user['just_registed']) {
                $udata =$this->weixin_user;
                $udata['just_registed']=0;
                $this->changeSession(C('weixin_session_key'), $udata);
                $round = 1;
            } else {
                $round = 2; //不是刚注册的用户,只能参与非注册轮抽奖了
            }
            $Api = D('Api');
            // $test_re =array();
            $mm = M('choujiang_history');
            $mg = M("choujiang_gift");
            // for($i=0;$i<10000;$i++){
            $ddd = $Api->gjjk($round, $this->weixin_user);
            if ($ddd['id'] > 0) {
                ;
                $mg->where(array('id' => $ddd['id']))->setInc('used_count');
            }
            $ma['gift_gailv'] = $ddd['gailv'];
            $ma['gift_id'] = $ddd['id'];
            $ma['user_id'] = $this->weixin_user['id'];
            $ma['random_val'] = $ddd['random_val'];
            $ma['created_at'] = time();
            $ma['round'] = $round;
            $history_id = $mm->add($ma);
            if (!$history_id) {
                throw new Exception("网络故障,刮奖失败,请稍候再试哦", 215);
            }
            // $test_re[$ddd['id']]['count'] +=1;
            // $test_re[$ddd['id']]['gailv'] = $ddd['gailv'];
            // }
            // dump($test_re);
        } catch (\Exception $exc) {
            $ddd = array('errcode' => $exc->getCode(), 'errmsg' => $exc->getMessage());
            $this->customReturn($exc->getCode(), $ddd);
        }
        //按接口文档定义的格式只返回必要的数据给前端
        $re_data = array();
        $re_data['id'] = $history_id;
        $re_data['gift_id'] = $ddd['id'];
        $re_data['gift_name'] = $ddd['name'];
        $re_data['need_contact_info'] = $ddd['need_contact_info'];
        $this->customReturn(1, $re_data);
    }

    /**　消费者中奖提交联系信息接口
     *　接口地址Home/Api/Cjgl_index
     * 　访问方式:GET,POST
     * 　传入参数:姓名： real_name(格式纯文本)，真实地址：real_address（格式纯文本）刮奖记录主键id(为数字大于0)
     *　返回值格式:array('succ'=>a1,'data'=>a2)
     * 　　如果a1==1时，表示接口成功调用，a2里data包含正确的返回值,返回值如下：
     * {"succ": 1,"data": {"data": "ok"}}
     * a1如果不等于1则表示出错了，返回data值都是错误代码，
     * 返回值如下：
     * 返回错误代码释义:
     * array('errcode'=>1009, 'errmsg'=>’参数ID错误’)
     * array('errcode'=>1100, 'errmsg'=>’姓名未填写’)
     * array('errcode'=>1102, 'errmsg'=>’您只能修改自己的中奖记录信息哦’)
     * array('errcode'=>1103, 'errmsg'=>’ID参数不存在’)
     * array('errcode'=>1101, 'errmsg'=>’ 地址未填写’)
     */
    public function Cjgl_index()
    {
        $ajaxdata = array();
        try {
            $id = I('id');
            $real_name = I('real_name');
            $real_address = I('real_address');
            if (ic_isPosInt($id)) {
                $map['id'] = $id;
            } else {
                $ajaxdata['errcode'] = '1009';
                $ajaxdata['errmsg'] = '姓名ID错误';
                $this->customReturn(1009, $ajaxdata);
            }
            if ($real_name == '') {
                $ajaxdata['errcode'] = '1100';
                $ajaxdata['errmsg'] = '姓名未填写';
                $this->customReturn(1100, $ajaxdata);
            }
            if ($real_address == '') {
                $ajaxdata['errcode'] = '1101';
                $ajaxdata['errmsg'] = '地址未填写';
                $this->customReturn(1101, $ajaxdata);
            }
            $datae = M('choujiang_history')->where($map)->field('id,real_name,real_address,user_id')->find();
            if (!$datae) {
                $ajaxdata['errcode'] = 1103;
                $ajaxdata['errmsg'] = 'ID $id 不存在';
                $this->customReturn(1103, $ajaxdata);
            }
            //只能修改自己的中奖纪录
            if ($datae['user_id'] != $this->weixin_user['id']) {
                $ajaxdata['errcode'] = "1102";
                $ajaxdata['errmsg'] = "您只能修改自己的中奖记录信息哦";
                $this->customReturn(1102, $ajaxdata);
            }
            $datae['id'] = $id;
            $datae['real_name'] = $real_name;
            $datae['real_address'] = $real_address;
            M('choujiang_history')->where($map)->save($datae);
            $ajaxdata['data'] = 'ok';

            $this->customReturn(1, $ajaxdata);

        } catch (\Exception $exc) {
            //返回失败信息
            $ajaxdata['errmsg'] = $exc->getMessage();
            $ajaxdata['errcode'] = 411;
            $this->customReturn(411, $ajaxdata);
        }

    }

    /**消费者上传照片和填写评论接口
     * 接口地址：/Home/Api/Nailphoto
     * 访问方式:get，post
     * 传入参数：指甲照片：photo_name(jpg,png,…)， 消费者评论：comments(纯文本)， 使用月长：use_month：(数字且大于0)，使用周长：use_week (数字大于0且小于等于4)
     * 返回值格式：array('succ'=>a1,'data'=>a2)
     * 如果a1==1时，表示接口成功调用，a2里data包含正确的返回值:{"succ": 1,"data": {"data": "ok"}}
     * a1如果不等于1则表示出错了，返回data值都是错误代码，返回错误代码释义:返回值如下：
     * array('errcode'=>101, 'errmsg'=>’您上传的图片格式不对,请检查’)
     * array('errcode'=>1101, 'errmsg'=>’您的图片未上传成功,请重试’)
     * array('errcode'=>113, 'errmsg'=>’使用时长(月)需填写哦’)
     * array('errcode'=>114, 'errmsg'=>'请选择使用时长(周)’)
     */

    public function Nailphoto()
    {
        $ajaxdata = array();
        try {
            $photo_name = I('photo_name');
            $comments = I('comments', '');
            $use_month = I('use_month', 0);
            $use_week = I('use_week', 0);
            $pmodel = D('NailPhoto');
            $pmodel->newRecord($photo_name, $this->weixin_user['id'], $comments, $use_month, $use_week);
            //     $ddd=explode('.',$photo_name);
            // if(($ddd['1']=='jpg'|| $ddd['1']=='png') and $ddd['1']!=''){
            //     $ma['photo_name']=$photo_name;
            // }else{
            //     $ajaxdata['errcode'] = '111';
            //     $ajaxdata['errmsg'] ='图片格式不对,图片格式只支持png,jpg';
            //     $this->customReturn(111,$ajaxdata);
            // }
            // if(ic_checkUnEmpty($comments)){
            //     $ma['comments']=$comments;
            // }else{
            //     $ajaxdata['errcode']=112;
            //     $ajaxdata['errmsg']="评论没有写";
            //     $this->customReturn(112,$ajaxdata);
            // }
            // if(ic_isPosInt($use_month)){
            //     $ma['use_month']=$use_month;
            // }else{
            //     $ajaxdata['errcode']=113;
            //     $ajaxdata['errmsg']='月数格式不对或者未勾选';
            //     $this->customReturn(113,$ajaxdata);
            // }
            // if($use_week>0 && $use_week<=4){
            //     $ma['use_week']=$use_week;
            // }else {
            //     $ajaxdata['errcode'] = 114;
            //     $ajaxdata['errmsg'] = "周数格式不对或者未勾选";
            //     $this->customReturn(114, $ajaxdata);
            // }
            //     $ma['user_id']= $this->weixin_user['id'];
            //     M('nail_photo')->add($ma);
            $ajaxdata['data'] = 'ok';
            $this->customReturn(1, $ajaxdata);
        } catch (\Exception $exc) {
            //返回失败信息
            // $ajaxdata['errcode'] = $exc->getMessage();
            // $ajaxdata['errmsg'] = 411;
            $succ = $exc->getCode() == 1 ? -1 : $exc->getCode();
            $datas = array('errcode' => $succ, 'errmsg' => $exc->getMessage());
            $this->customReturn($succ, $datas);

        }

    }

    /**店员注册接口
     *接口地址：Home/Api/clerk
     *访问方式:GET, POST
     * 传入参数:姓名：realname（纯文本）手机：phone（手机格式需11位）省：r_province(格式为纯文本)市：r_city(格式为纯文本)药房名称: yaofang_name
     * 门店名称: store_name 销售经理编号: manager_id (正整数)
     * 返回值:array('succ'=>a1,'data'=>a2)
     * 如果a1==1时，表示接口成功调用，a2里data包含正确的返回值，
     * {"succ": 1,"data": {"nickname": null,"realname": "f","headimgurl": null,"yaofang_name": "天天药房","store_name": "曹阳店"}}
     * a1如果不等于1则表示出错了，返回data值都是错误代码，
     * 返回错误代码释义:
     * 返回值如下：
     * array('errcode'=>114, 'errmsg'=>’参数realname未填写’)
     * array('errcode'=>117, 'errmsg'=>’phone参数格不对或者未填写’)
     * array('errcode'=>90, 'errmsg'=>’药房未填写’)
     * array('errcode'=>91, 'errmsg'=>’门店未填写’)
     * array('errcode'=>92, 'errmsg'=>’销售经理编号不正确,请检查扫描的二维码’)
     * array('errcode'=>93, 'errmsg'=>’经理编号未填写’)
     * array('errcode'=>11, 'errmsg'=>’ 手机号已存在’)
     * array('errcode'=>116, 'errmsg'=>’ 省份未找到或者没有填写’)
     * array('errcode'=>126, 'errmsg'=>’ 城市未找到或者没有填写’)
     * array('errcode'=>2001, 'errmsg'=>’网络原因保存您的注册信息未成功,请稍候再试’)
     */

    public function clerk()
    {
        $ajaxdata = array();
        try {
            $d = C('shengshi');//获取省份配置
            $dd = json_decode($d, true);//转换数组
            $realname = I('realname');
            $phone = I('phone');
            $r_province = I('r_province');
            $r_city = I('r_city');
            $yaofang_name = I('yaofang_name');
            $store_name = I('store_name');
            $manager_id = I('manager_id');
            $sale_managers = C('sale_managers');
            if (ic_checkUnEmpty($realname)) {
                $map['realname'] = $realname;
            } else {
                $ajaxdata['errcode'] = '114';
                $ajaxdata['errmsg'] = '姓名未填写';
                $this->customReturn(114, $ajaxdata);
            }
            $datae = M('apply_user')->field('phone')->select();//验证手机号唯一
            foreach ($datae as $k => $value) {
                if ($phone == $datae[$k]['phone']) {
                    $ajaxdata['errcode'] = 11;
                    $ajaxdata['errmsg'] = '手机号已存在';
                    $this->customReturn(11, $ajaxdata);
                }
            }
            if (ic_isCellPhone($phone) == ture) {
                $map['phone'] = $phone;
            } else {
                $ajaxdata['errcode'] = 117;
                $ajaxdata['errmsg'] = "手机格式不对或者未填写";
                $this->customReturn(117, $ajaxdata);
            }
            $ghh = false;//设定默认值
            $j = 0;
            foreach ($dd['citylist'] as $k => $value) {
                if ($r_province == $value['p']) {
                    $ghh = true;
                    $j = $k;
                }
            }
            if (!$ghh) {
                $ajaxdata['errcode'] = 116;
                $ajaxdata['errmsg'] = "请选择省份";
                $this->customReturn(116, $ajaxdata);
            }
            if ($r_province) {
                $map['r_province'] = $r_province;
            }
            $bbb = false;//设定默认值
            foreach ($dd['citylist'][$j]['c'] as $k => $value) {
                if ($r_city == $value['n']) {
                    $bbb = true;
                }
            }
            if (!$bbb) {
                $ajaxdata['errcode'] = 126;
                $ajaxdata['errmsg'] = '请选择城市';
                $this->customReturn(126, $ajaxdata);
            }
            if ($r_city) {
                $map['r_city'] = $r_city;
            }
            if (ic_checkUnEmpty($yaofang_name)) {
                $map['yaofang_name'] = $yaofang_name;
            } else {
                $ajaxdata['errcode'] = '90';
                $ajaxdata['errmsg'] = '请输入您的药店名称';
                $this->customReturn(90, $ajaxdata);
            }
            if (ic_checkUnEmpty($store_name)) {
                $map['store_name'] = $store_name;
            } else {
                $ajaxdata['errcode'] = '91';
                $ajaxdata['errmsg'] = '请输入您的门店名称';
                $this->customReturn(91, $ajaxdata);
            }
            if (ic_checkUnEmpty($manager_id)) {
                if ($sale_managers[$manager_id]) {
                    $map['manager_id'] = $manager_id;
                } else {
                    $ajaxdata['errcode'] = '92';
                    $ajaxdata['errmsg'] = '销售负责人编号不正确,请检查扫描的二维码';
                    $this->customReturn(92, $ajaxdata);
                }
            } else {
                $ajaxdata['errcode'] = '93';
                $ajaxdata['errmsg'] = '没有指定销售负责人,请检查扫描的二维码';
                $this->customReturn(93, $ajaxdata);
            }
            $data_id = $this->weixin_user['id'];
            $map['type'] = 2;
            //$data_id = M('apply_user')->add($map);
            //保存店员信息
            $updateRe = M('apply_user')->where('id=' . $data_id)->save($map);
            if (!$updateRe) {
                $ajaxdata['errcode'] = 2001;
                $ajaxdata['errmsg'] = "网络原因保存您的注册信息未成功,请稍候再试";
                $this->customReturn(2001, $ajaxdata);
            }
            //$data = M('apply_user')->where(array('id' => $data_id))->field('nickname,realname,headimgurl,yaofang_name,store_name')->find();
            $data = M('apply_user')->where(array('id' => $data_id))->find();
            $this->changeSession(C('weixin_session_key'), $data);
            //注册加分
            $this->points_index(1,0,false);
            $this->customReturn(1, 
                array('nickname'=>$data['nickname'],
                    'realname'=>$data['realname'],
                    'headimgurl'=>$data['headimgurl'],
                    'yaofang_name'=>$data['yaofang_name'],
                    'store_name'=>$data['store_name']));
        } catch (\Exception $exc) {
            //返回失败信息
            $ajaxdata['errcode'] = $exc->getCode() == 1 ? -1 : $exc->getCode();
            $ajaxdata['errmsg'] = $exc->getMessage();
            $this->customReturn($ajaxdata['errcode'], $ajaxdata);
        }

    }

    /**根据店员姓名和手机号查询门店名称接口
     *接口地址:/Home/Api/dysjjk
     * 访问方式:GET ,POST
     * 传入参数:手机：phone；姓名：realname(纯文本)；
     * 返回值:array('succ'=>a1,'data'=>a2)
     * 如果a1==1时，表示接口成功调用，a2里data包含正确的返回值，
     * {"succ": 1,"data": {"id": "224","realname": "f","phone": "18117364673","store_name": "安徽大家"}}
     * a1如果不等于1则表示出错了，返回data值都是错误代码，
     * 返回错误代码释义:
     * 返回值如下：
     * array('errcode'=>201, 'errmsg'=>’参数realname未填写或者没有’)
     * array('errcode'=>107, 'errmsg'=>’参数phone未填写或者格式不对’)
     * array('errcode'=>204, 'errmsg'=>’数据返回失败’)
     */
    public function dysjjk()
    {
        $ajaxdata = array();
        try {
            $realname = I('realname');
            $phone = I('phone');
            if (ic_checkUnEmpty($realname)) {
                $map['realname'] = $realname;
            } else {
                $ajaxdata['errcode'] = '201';
                $ajaxdata['errmsg'] = '姓名未填写';
                $this->customReturn(201, $ajaxdata);
            }
            if (ic_isCellPhone($phone) == ture) {
                $map['phone'] = $phone;
            } else {
                $ajaxdata['errmsg'] = '手机格式不对或者未填写';
                $ajaxdata['errcode'] = 107;
                $this->customReturn(107, $ajaxdata);
            }
            $map['type'] = 2;
            $data_id = M('apply_user')->where($map)->field('id,realname,phone,store_name')->find();
            if (empty($data_id)) {
                $ajaxdata['errmsg'] = "数据返回失败";
                $ajaxdata['errcode'] = 204;
                $this->customReturn(204, $ajaxdata);
            }
            $ajaxdata = 1;
            $this->customReturn($ajaxdata, $data_id);
        } catch (\Exception $exc) {
            //返回失败信息
            $ajaxdata['errmsg'] = $exc->getMessage();
            $ajaxdata['errcode'] = 411;
            $this->customReturn(411, $ajaxdata);
        }

    }

    /**当前店员积分排名和全部店员积分top 3查询接口
     *接口地址:/Home/Api/dtdu_index
     * 访问方式:GET,POST
     * 传入参数: user_id
     * 返回值:array('succ'=>a1,'data'=>a2)
     * 如果a1==1时，表示接口成功调用，a2里data包含正确的返回值，
     * {"succ": 1,"data": {"id": "1","realname": "aa ","points": "10","store_name": "曹阳店","Current ranking": "4","Top3 ranking": [{"id": "103","realname": "2","points": "111","store_name": null},{"id": "101","realname": "2","points": "56","store_name": null},{"id": "102","realname": "2","points": "55","store_name": null}]}}
     * Key：id=用户id，realname=姓名，points=当前剩余积分，store_name=店名，Current ranking=当前排名，Top3 ranking=top3排名
     * a1如果不等于1则表示出错了，返回data值都是错误代码，、
     * array('errcode'=>218, 'errmsg'=>’数据返回失败’)
     */
    public function dtdu_index()
    {
        $ajaxdata = array();
        try {

            $map['type'] = 2;
            $ma['id'] = $this->weixin_user['id'];
            $map['points'] = array('gt', '(select points from eosi_apply_user where id=' . $ma['id']);
            $data_id = M('apply_user')->where($map)->count();//当前排名
            $dqd_yuan = M('apply_user')->where(array('id' => $ma['id']))->field('id,realname,points,store_name,headimgurl')->find();
            $dqd_yuan['Current ranking'] = $data_id;
            $top3 = M('apply_user')->order('points desc ')->limit(3)->field('id,realname,points,store_name')->select();
            $dqd_yuan['Top3 ranking'] = $top3;
            if (empty($dqd_yuan)) {
                $ajaxdata['errcode'] = 218;
                $ajaxdata['errmsg'] = "数据返回失败";
                $this->customReturn(218, $ajaxdata);
            }
            $ajaxdata = 1;
            $this->customReturn($ajaxdata, $dqd_yuan);
        } catch (\Exception $exc) {
            //返回失败信息
            $ajaxdata['errmsg'] = $exc->getMessage();
            $ajaxdata['errcode'] = 411;
            $this->customReturn(411, $ajaxdata);
        }

    }

    /**当前店员积分明细查询接口(需分页查询)
     *接口地址Home/Api/dymx_index
     *Cur_page(数字不能未0)  要查询第几页数据
     *返回值:
     * array('succ'=>a1,'data'=>a2)
     * 如果a1==1时，表示接口成功调用，a2里data包含正确的返回值，
     * {"succ": 1,"data": [{"created_at": "1974-11-01 15:55:45","type": "分享文章","points_changed": "2"},{"created_at": "1970-01-01 08:37:13",
     * "type": "分享文章","points_changed": "2"}]}
     * a1如果不等于1则表示出错了，返回data值都是错误代码，、
     * array('errcode'=>155, 'errmsg'=>’数字要大于0’)
     * array('errcode'=>156, 'errmsg'=>’’)
     *
     */
    public function dymx_index()
    {
        $ajaxdata = array();
        try {
            $cur_page = I('cur_page');

            if (ic_isPosInt($cur_page)) {
                $curp = $cur_page;
            } else {
                $ajaxdata['errcode'] = "155";
                $ajaxdata['errmsg'] = "数字要大于0";
                $this->customReturn(155, $ajaxdata);
            }
            $m = 10;
            $this->user_model = M('points_history');

            $count_id = $this->user_model->where(array('user_id' => $this->weixin_user['id']))->count();
            $t_pages = floor($count_id / $m);
            if ($count_id % $m != 0) {
                $t_pages += 1;
            }
            $curp = ($curp > $t_pages) ? $t_pages : $curp;
            $curp = $curp>=1?$curp:1;
            $ee = $this->user_model->where(array('user_id' => $this->weixin_user['id']))->field('created_at,type,points_changed')->limit(($curp - 1) * $m, $m)->select();

            foreach ($ee as $k => $value) {
                if ($value['type'] == '1') {
                    $ee[$k]['type'] = "注册";;
                } elseif ($value['type'] == '2') {
                    $ee[$k]['type'] = "分享文章";
                } elseif ($value['type'] == '3') {
                    $ee[$k]['type'] = "兑换礼品";
                } elseif ($value['type'] == '4') {
                    $ee[$k]['type'] = "参与互动";
                } else {
                    $ee[$k]['type'] = "积分过有效期";
                }
                $ee[$k]['created_at'] = date('Y-m-d', $value['created_at']);

            }
            $ajaxdata = 1;
            $this->customReturn($ajaxdata, array('content' => $ee, 'totalpages' => $t_pages));
        } catch (\exception $ex) {
            //返回失败信息
            $ajaxdata['errmsg'] = $ex->getMessage();
            $ajaxdata['errcode'] = 411;
            $this->customReturn(411, $ajaxdata);
        }
    }

    /**当前店员积分变动接口
     * 接口地址:/Home/Api/points_index
     * 访问方式get，post
     * 传入参数:
     * 积分变动类型：type(数字大于0，小于等于5)
     * 积分变动对象object_id:
     * (分享文章类型为文章id,
     * 兑换礼品类型为礼品id,
     * 参与互动类型为互动事件id
     * 返回值:
     * array('succ'=>a1,'data'=>a2)
     * 如果a1==1时，表示接口成功调用，a2里data包含正确的返回值，
     * {“usre_id”:”xxxx”;” points_changed”:”xxxx”}
     * 返回错误代码释义:
     * a1如果不等于1则表示出错了，返回data值都是错误代码，、
     * array('errcode'=>1555, 'errmsg'=>’type要大于0小于等于5’)
     * array('errcode'=>1665, 'errmsg'=>’object_id要大于0’)
     *array('errcode'=>165, 'errmsg'=>’数据返回失败’)
     */
    public function points_index($mytype=false,$myobject_id=false,$exit_a=true)
    {
        if($this->weixin_user['type']!=2){
            //非店员不加分
            // throw new \Exception("参数有误,请检查(utype)", 1111);
            $ajaxdata['errmsg'] = '';
            $ajaxdata['errcode'] = 1;
            $this->customReturn($ajaxdata['errcode'], $ajaxdata);
        }
        $ajaxdata = array();
        try {
            $type = $mytype===false?I('type'):$mytype;
            $object_id = $myobject_id===false?I('object_id'):$myobject_id;
            $cc = C('jifenliexing');
            $points = M('apply_user')->where(array('id' => $this->weixin_user['id']))->field('points')->find();
            $fdf = implode($points);
            if (array_key_exists($type, $cc)) {
                $add['type'] = $type;
                if ($type == '1') {
                    $add['points_changed'] = $cc[$type];
                    $add['points_left'] = $fdf + $cc[$type];
                } elseif ($type == '2') {
                    $add['points_changed'] = $cc[$type];
                    $add['points_left'] = $fdf + $cc[$type];
                } elseif ($type == '3') {
                    $add['points_changed'] = $cc[$type];
                    $add['points_left'] = $fdf + $cc[$type];
                } elseif ($type == '4') {
                    $add['points_changed'] = $cc[$type];
                    $add['points_left'] = $fdf + $cc[$type];
                } else {
                    $add['points_changed'] = $cc[$type];
                    $add['points_left'] = $fdf + $cc[$type];
                }
            } else {
                // $ajaxdata['errcode'] = 1555;
                // $ajaxdata['errmsg'] = "参数有误,请检查";
                // $this->customReturn(1555, $ajaxdata);
                throw new \Exception("参数有误,请检查(t)", 1555);
            }
            if (ic_isPosInt($object_id)||$object_id==0) {
                $add['object_id'] = $object_id;
            } else {
                // $ajaxdata['errcode'] = 1665;
                // $ajaxdata['errmsg'] = "数字要大于0";
                // $this->customReturn(1665, $ajaxdata);
                throw new \Exception("参数有误,请检查(obj_id)", 1665);
            }
            //一般来说同类型加分只能做一次
            $exist_map=array();
            $exist_map['user_id']=$this->weixin_user['id'];
            $exist_map['type']=$type;
            $exist_map['object_id']=$object_id;
            $re = M('points_history')->where($exist_map)->find();
            if($re){
                $ajaxdata['errmsg'] = '';
                $ajaxdata['errcode'] = 1;
                $this->customReturn($ajaxdata['errcode'], $ajaxdata);
            }
            $add['user_id']=$this->weixin_user['id'];
            $add['created_at']=time();
            $re = M('points_history')->add($add);
            if(!$re){
                throw new \Exception("网络原因提交数据失败请稍候再试", 786);
            }
            //用户总分加上
            $User = M("apply_user"); // 实例化User对象
            $User->where('id='.$this->weixin_user['id'])->setInc('points',$add['points_changed']); 
            // $join = 'left join eosi_apply_user eg on ejh.user_id=eg.id and eg.type=2';

            // $dasa = M('points_history')->alias('ejh')->join($join)->where(array('user_id' => $this->weixin_user['id']))->field('eg.realname,ejh.points_changed')->find();

            // $ajaxdata = $dasa;
            // if ($dasa == '') {
            //     $ajaxdata['errcode'] = "165";
            //     $ajaxdata['errmsg'] = "数据返回失败";
            //     $this->customReturn(165, $ajaxdata);
            // }
            if($exit_a===false){
                return $re;
            }
            $this->customReturn(1, $re);
        } catch (\exception $exc) {
            if($exit_a===false){
                throw $exc;
                return;
            }
            //返回失败信息
            $ajaxdata['errmsg'] = $exc->getMessage();
            $ajaxdata['errcode'] = $exc->getCode()==1?-1:$exc->getCode();
            $this->customReturn($ajaxdata['errcode'], $ajaxdata);
        }
    }

    // public function debug_clear_uinfo(){
    //     $uid=$this->weixin_user['id'];
    //     $this->changeSession(C('weixin_session_key'), null);
    //     $map['id']=$uid;
    //     M('apply_user')->where($map)->delete();
    //     $m['user_id']=$uid;
    //     M('choujiang_history')->where($m)->delete();
    //     M('nail_photo')->where($m)->delete();
    //     M('points_history')->where($m)->delete();
    //     $ajaxdata['errmsg'] = '您的信息已清除,请重新扫描2唯码进入系统(仅供测试用)';
    //     $ajaxdata['errcode'] = 1;
    //     $this->customReturn($ajaxdata['errcode'], $ajaxdata);
    // }

}
